package model

import (
	"crypto/rand"
	"fmt"
	"math/big"
	"parking-lot-go-admin/config"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var Db *gorm.DB
var err error

func init() {

	// 读取配置文件
	dbSection := config.Cfg.Section("DATABASE")

	dbHost := dbSection.Key("DB_HOST").String()
	dbPort := dbSection.Key("DB_PORT").String()
	dbName := dbSection.Key("DB_DATABASE").String()
	dbUsername := dbSection.Key("DB_USERNAME").String()
	dbPassword := dbSection.Key("DB_PASSWORD").String()

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbUsername, dbPassword, dbHost, dbPort, dbName)

	Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		panic(err.Error())
	}
}

func DateToInt(timeStr string) int {
	layout := "2006-01-02 15:04:05"
	parsedTime, err := time.Parse(layout, timeStr)
	if err != nil {
		fmt.Println("Failed to parse time:", err)
		return 0
	}

	// 转换为 Unix 时间戳
	timestamp := parsedTime.Unix()

	intTimestamp := int(timestamp)

	fmt.Println("Timestamp:", timestamp)
	return intTimestamp
}

// 生成随机字符串
func GenerateRandomString(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	bytes := make([]byte, length)
	max := big.NewInt(int64(len(charset)))

	for i := range bytes {
		n, err := rand.Int(rand.Reader, max)
		if err != nil {
			panic(err)
		}
		bytes[i] = charset[n.Int64()]
	}

	return string(bytes)
}
